package com.logic.landseaserver.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.logic.system.service.IConfigurationService;
import com.logic.system.service.impl.ConfigurationService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.bind.RelaxedPropertyResolver;
import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import com.logic.common.exception.BusinessException;
import com.logic.common.security.SecurityUtils;
import com.logic.common.util.QueryUtil;
import com.logic.landseaserver.common.LandseaErrorMessageEnum;
import com.logic.landseaserver.common.exception.LandseaBusinessException;
import com.logic.landseaserver.common.util.SMSUtil;
import com.logic.landseaserver.common.util.StringTools;
import com.logic.landseaserver.domain.Message;
import com.logic.landseaserver.persistence.read.MessageReadMapper;
import com.logic.landseaserver.persistence.write.MessageWriteMapper;
import com.logic.landseaserver.service.IMessageService;

import net.sf.json.JSONObject;

@Service
public class MessageServiceImpl implements IMessageService, EnvironmentAware {

    private static RelaxedPropertyResolver propertyResolver;

    private static final String ENV_SENDMSG_INFO = "logic.sms.sendmsg.";
    private static final String GET_TOKEN_URL = "tokenUrl";
    private static final String USER_NAME = "userName";
    private static final String MESSGAG_ENV = "messgeEnv";
    private static final String PASS_WORD = "password";
    private static final String SEND_MSG_URL = "msgUrl";
    private static final String ALL_VERIFYCODE = "verifyCode";

    @Autowired
    private MessageWriteMapper messageWriteMapper;

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private MessageReadMapper messageReadMapper;
    @Autowired
    private IConfigurationService configurationService;

    @Override
    public Map<String, Integer> queryMessageCount() {
        Integer userId = SecurityUtils.getCurrentOAuthLogin().getUserId();
        Integer messageCount = messageReadMapper.queryMessageCount(userId);
        //Integer couponCount = userCouponReadMapper.couponCount(userId); TODO
        Map<String, Integer> map = new HashMap<String, Integer>();
        messageCount = messageCount != 0 ? 1 : 0;
        //couponCount = couponCount == null ? 0 : couponCount;
        map.put("messageCount", messageCount);
        //map.put("couponCount", couponCount);
        return map;
    }

    @Override
    public Boolean queryCountsByPhone(String phone) {
        Integer counts = messageReadMapper.queryCountsByPhone(phone);
        /*Properties property = new Properties();
        InputStream is = Object.class.getResourceAsStream("/resource.properties");
        try {
            property.load(is);
        } catch (IOException e) {
            LOG.error("queryCountsByPhone error.", e);
        }*/
        String params = "10";
        if (counts == null || counts.compareTo(Integer.parseInt(params)) < 0) {
            return true;
        }
        return false;
    }

    @Override
    public void setEnvironment(Environment arg0) {
        propertyResolver = new RelaxedPropertyResolver(arg0, ENV_SENDMSG_INFO);
    }

    @Override
    public int insert(Object obj) throws BusinessException {
        Message message = (Message) obj;
        validateForInsert(message);

        if (message.getStatus() == null) {
            message.setStatus(0);
        }
        message.updateCommonInfo(null);
        return messageWriteMapper.insertSelective(message);

    }

    @Override
    public Object get(Integer id) throws BusinessException {
        return null;
    }

    @Override
    public void update(Object obj) throws BusinessException {
        Message message = (Message) obj;
        validateForUpdate(message);
        message.updateCommonInfo(-1);
        messageWriteMapper.updateByPrimaryKeySelective(message);
    }

    @Override
    public Integer updateMessageStatus() {
        return messageWriteMapper.updateMessageStatus(SecurityUtils.getCurrentOAuthLogin().getUserId());
    }


    @Override
    public void delete(String ids) throws BusinessException {

    }

    @Override
    public List<Object> query(QueryUtil queryUtil) {
        return null;
    }

    @Override
    public Boolean validate(Object obj) throws BusinessException {
        return null;
    }

    @Override
    public Boolean validateForInsert(Object obj) throws BusinessException {
        Boolean result = true;
        Message message = (Message) obj;
        if (message.getType() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.INSERT_MESSAGE_TYPE_IS_NULL);
        }
        if (StringUtils.isEmpty(message.getMobilePhone())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.INSERT_MESSAGE_PHONE_IS_NULL);
        }
        if (!StringTools.isPhone(message.getMobilePhone())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.INSERT_MESSAGE_PHONE_IS_VALID);
        }
        if (StringUtils.isEmpty(message.getParams())) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.INSERT_MESSAGE_PARAM_IS_NULL);
        }
        if (message.getStatus() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.INSERT_MESSAGE_STATUS_IS_NULL);
        }
        return result;
    }

    @Override
    public Boolean validateForUpdate(Object obj) throws BusinessException {
        Boolean result = true;
        Message message = (Message) obj;
        if (message.getId() == null) {
            throw new LandseaBusinessException(LandseaErrorMessageEnum.UPDATE_MESSAGE_ID_IS_NULL);
        }

        return result;
    }

    @Override
    public Boolean validateForDelete(Object obj) throws BusinessException {
        return null;
    }

    @Override
    public List<Message> queryMessage(Message message) {
        List<Message> list = messageReadMapper.querySendMessage(message);
        for (int i = 0; list.size() > 0 && i < list.size(); i++) {
            Message obj = list.get(i);
            if(!this.queryCountsByPhone(obj.getMobilePhone())){
                continue;
            }
            JSONObject sendMsgJson = new JSONObject();
            sendMsgJson.put(GET_TOKEN_URL, propertyResolver.getProperty(GET_TOKEN_URL, String.class, null));
            sendMsgJson.put(USER_NAME, propertyResolver.getProperty(USER_NAME, String.class, null));
            sendMsgJson.put(PASS_WORD, propertyResolver.getProperty(PASS_WORD, String.class, null));
            sendMsgJson.put(SEND_MSG_URL, propertyResolver.getProperty(SEND_MSG_URL, String.class, null));
            sendMsgJson.put("message_code",
                    propertyResolver.getProperty(obj.getType().getCode(), String.class, null));

            String  messageEnv =  propertyResolver.getProperty(MESSGAG_ENV, String.class, null);
            boolean result = false;
            if(messageEnv != null && ("live").equals(messageEnv)){
                String signName = configurationService.getStringValue(ConfigurationService.SEND_MSG_SIGN_NAME);
                result = SMSUtil.sendSms("", obj.getMobilePhone(), " " + obj.getParams().toString(),signName);
            }
            logger.info("send msg result is "+result);
            if (result) {
                obj.setStatus(1);
                obj.setSendTime(new Date());
                try {
                    update(obj);
                } catch (Exception ew) {
                    ew.printStackTrace();
                    logger.info("消息id为" + obj.getId() + "修改状态失败！");
                }
            }
        }
        return null;
    }

//    @Override
//    public List<Message> queryMessageList() {
//        return messageReadMapper.queryMyMessage(SecurityUtils.getCurrentOAuthLogin().getUserId());
//    }


}